<template>
    <section class="Power_container">
        <el-tree
            :data="data"
            :show-checkbox="showCheckbox"
            ref="tree"
            node-key="id"
            default-expand-all
            :default-checked-keys="checked"
            :props="defaultProps"
        >
            <template slot-scope="{ data }">
                <div class="power-panel">
                    <i v-if="data.is_menu == 'True'" class="iconfont icon-caidan" />
                    <i v-else class="iconfont icon-fanghuliliang" />
                    <span v-if="data.is_menu == 'True'" class="menu">{{ data.name }}</span>
                    <span v-else class="power">{{ data.name }}</span>
                </div>
            </template>
        </el-tree>
    </section>
</template>

<script>
import power_api from "@/common/api/power";

export default {
    props: {
        selectedPowers: {
            type: Array,
            // 默认值,用函数返回值
            default: function () {
            return [];
        },
        },
        showCheckbox: {
            type: Boolean,
            default: false,
        },
    },

    computed: {
        checked() {
            return this.selectedPowers.map((m) => m.power_id);
        },
    },

    data() {
        return {
            data: [],
            defaultProps: {
                children: "children",
                label: "name",
            },
        };
    },

    methods: {
        setData(powers, parent_id) {
            let nodes = [];
            powers.map((p) => {
                if (p.parent_id == parent_id) {
                    let node = {
                        id: p.id,
                        name: p.name,
                        is_menu: p.is_menu,
                        parent_id: p.parent_id,
                    };

                    let children = this.setData(powers, p.id);
                    if (children.length > 0) node.children = children;
                    nodes.push(node);
                }
            });
            return nodes;
        },

        async getPowers() {
            const result = await power_api.getListAsync();
            this.data = this.setData(result.data, 0);
        },

        getSelectedPowers() {
            return this.$refs.tree.getCheckedNodes(false, true);
        },
    },

    mounted() {
        this.getPowers();
    },
};
</script>

<style lang="scss" scoped>
.power-panel {
    display: flex;
    align-items: center;

    .power {
        margin-left: 5px;
        font-size: 1.4rem;
        color: #666;
    }

    .menu {
        margin-left: 5px;
        font-size: 1.4rem;
        color: #333;
        font-weight: bold;
    }
}
</style>
